package com.cskaoyan.controller.system;

import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.po.MarketRole;
import com.cskaoyan.bean.vo.GetPermissionsRoleVO;
import com.cskaoyan.bean.vo.MarketRoleVO;
import com.cskaoyan.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Auther: Yang Yi-zhou
 * @Date: 2022/9/6 20:30
 * @Description:
 */
@RestController
@RequestMapping("admin/role")
@Cacheable(value = "admin::role",keyGenerator = "customKeyGenerator")
public class RoleController {

    @Autowired
    RoleService roleService;

    @RequestMapping("options")
    public BaseRespVo optionsRole() {
        CommonData<MarketRoleVO> data = roleService.optionsRole();
        return BaseRespVo.ok(data);
    }

    @GetMapping("permissions")
    public BaseRespVo getPermissionsRole(Integer roleId) {
        GetPermissionsRoleVO data = roleService.getPermissionsRole(roleId);
        return BaseRespVo.ok(data);
    }

    @PostMapping("permissions")
    @CacheEvict(value = "admin::role", allEntries = true)
    public BaseRespVo postPermissionsRole(@RequestBody Map map) {
        Integer roleId = (Integer) map.get("roleId");
        List<String> permissions = (List<String>) map.get("permissions");
        roleService.postPermissionsRole(roleId, permissions);
        return BaseRespVo.ok();
    }

    @RequestMapping("list")
    public BaseRespVo listRole(Integer page, Integer limit, String sort, String order) {
        CommonData<MarketRole> data = roleService.listRole(page, limit, sort, order);
        return BaseRespVo.ok(data);
    }

    @RequestMapping("create")
    @CacheEvict(value = "admin::role", allEntries = true)
    public BaseRespVo createRole(@RequestBody MarketRole marketRole) {
        if (roleService.isDuplicateName(marketRole.getName())) {
            return BaseRespVo.invalidData("角色名称已存在");
        }
        MarketRole data = roleService.createRole(marketRole);
        return BaseRespVo.ok(data);
    }

    @RequestMapping("update")
    @CacheEvict(value = "admin::role", allEntries = true)
    public BaseRespVo updateRole(@RequestBody MarketRole marketRole) {
        if (roleService.updateRole(marketRole)) {
            return BaseRespVo.ok();
        }
        return BaseRespVo.invalidData("更新失败");
    }

    @RequestMapping("delete")
    @CacheEvict(value = "admin::role", allEntries = true)
    public BaseRespVo deleteRole(@RequestBody MarketRole marketRole) {
        if (roleService.deleteRole(marketRole)) {
            return BaseRespVo.ok();
        }
        return BaseRespVo.invalidData("删除失败");
    }
}
